package com.voicechat.firstmet.adapter;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.voicechat.firstmet.R;
import com.voicechat.firstmet.client.OssClient;
import com.voicechat.firstmet.client.OssConfig;
import com.voicechat.firstmet.utils.GlideLoadUtils;
import com.voicechat.firstmet.view.largerImage.PhotoView;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by administraot on 2017/12/1.
 */

public class PhotoAdapter extends PagerAdapter {
    private static final String TAG = "PhotoAdapter";
    /**
     * Fragment虽然不是上下文对象但是他有个方法getContext()对象
     * 我们使用Fragment是因为前面说到使用Glide加载图片时，Glide会根据传入的
     * Fragment或者Activity自行关联它们的生命周期，达到优化内存的效果。
     */
    private Context mContext;
    private ProgressBar progressBar;
    /**
     * 图片地址集合
     */
    private List<String> mList;
    /**
     * PhotoView集合，有多少个图片就创建多少个PhotoView。
     */
    private List<PhotoView> mPhoto = new ArrayList<>();
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                Bundle data = msg.getData();
                byte[] bitmap = data.getByteArray("bitmap");
                //String tag = data.getString("tag");
                PhotoView view = (PhotoView) msg.obj;
                GlideLoadUtils.getInstance().glideLoad(mContext,bitmap,view);
               /* GlideApp.with(mContext)
                        .load(bitmap)
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(view);*/
            }
        }
    };
    /**
     * 构造方法，初始化适配器
     *
     * @param mContext
     * @param mList
     */
    public PhotoAdapter(Context mContext, List<String> mList, ProgressBar progressBar) {
        this.mContext = mContext;
        this.mList = mList;
        this.progressBar = progressBar;
        // initPhoto();
    }

    public interface OnPageClickListener {
        void onClick(View view, int position);
        //void onLongClick(View view,int position);
    }

    public OnPageClickListener mOnPageClickListener;

    public void addOnPageClickListener(OnPageClickListener listener) {
        mOnPageClickListener = listener;
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public void notifyDataSetChanged() {
//        initPhoto();
        super.notifyDataSetChanged();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        PhotoView p = new PhotoView(mContext);
        // 设置图片显示
        p.setScaleType(ImageView.ScaleType.FIT_CENTER);
        p.enable();
        String imgUrl = mList.get(position);
        if (!imgUrl.toLowerCase().startsWith("file") && !imgUrl.toLowerCase().startsWith("http")) {
           // imgUrl = HTTPAPI.CIRCLE_PIC + imgUrl;
        }
        Log.i(TAG, "imgUrl:" + imgUrl);
        progressBar.setVisibility(View.GONE);
        //p.setImageResource(R.drawable.ic1);
        /*Glide.with(mContext).load(imgUrl)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(R.drawable.ic1)
                .into(new GlideDrawableImageViewTarget(p) {
                    @Override
                    public void onLoadStarted(Drawable placeholder) {
                        super.onLoadStarted(placeholder);
                        progressBar.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);
                        progressBar.setVisibility(View.GONE);
                    }

                    @Override
                    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
                        super.onResourceReady(resource, animation);
                        progressBar.setVisibility(View.GONE);
//                mAttacher.update();
                    }
                });*/
       // setImage(imgUrl,p);
        if(!TextUtils.isEmpty(imgUrl)) {
            if (!imgUrl.equals(p.getTag(R.id.image_icon))) {
                // 加载图片
                p.setTag(R.id.image_icon, imgUrl);
                GlideLoadUtils.getInstance().glideLoad(mContext, OssConfig.OSS_HTTP + imgUrl,
                        p);
                // setImage(string, holder.get(R.id.circle_picture));
            }
        }
        // 然后将加载了图片的photoView添加到viewpager中，并且设置宽高
        container.addView(p, ViewPager.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        p.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mOnPageClickListener.onClick(view, position);
            }
        });
        p.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
               // mOnPageClickListener.onLongClick(v,position);
                return true;
            }
        });
        return p;

    }
    private void setImage(String url, View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                OssClient.getInstance().init(mContext).fileDownload(url, new OssClient.OnDownloadFile() {
                    @Override
                    public void onDownFileSuccess(InputStream inputStream) {
                        byte[] bitmap = null;
                        try {
                            bitmap = OssConfig.readInputStreamToByte(inputStream);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        //if(view.getTag() != null && view.getTag().equals(url)) {
                        Message message = Message.obtain();
                        message.what = 1;
                        message.obj = view;
                        Bundle bundle = new Bundle();
                        //bundle.putString("tag",url);
                        bundle.putByteArray("bitmap", bitmap);
                        message.setData(bundle);
                        handler.sendMessage(message);
                        //  }
                    }
                    @Override
                    public void onDownFileProgress(String progress) {

                    }
                });
            }
        }).start();

    }
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
//        container.removeView(mPhoto.get(position));
        container.removeView((View) object);
    }
}
